package com.sx.controller;


import com.sx.domain.Course;
import com.sx.domain.CourseVo;
import com.sx.domain.ResponseResult;
import com.sx.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseService courseService;

    @RequestMapping(value = "/findCourseByCondition")
    public ResponseResult findCourseByCondition(@RequestBody(required = false) CourseVo courseVo) {

        
        List<Course> list = courseService.findCourseByCondition(courseVo);
        return new ResponseResult(true, 200, "查询成功", list);
    }

    /**
     * 图片上传（支持GET/POST方法）
     */
    @RequestMapping(value = "/courseUpload", method = {RequestMethod.POST, RequestMethod.GET})
    public ResponseResult fileUpload(@RequestParam(value = "file", required = false) MultipartFile file,
                                     HttpServletRequest request) {
        // 如果是GET请求，返回提示信息
        if (request.getMethod().equals("GET")) {
            HashMap<String, String> info = new HashMap<>();
            info.put("message", "请使用POST方法上传文件");
            info.put("example", "POST /course/courseUpload 通过form-data上传文件，参数名为file");
            return new ResponseResult(true, 200, "接口信息", info);
        }

        // 判断文件是否为空
        if (file == null || file.isEmpty()) {
            return new ResponseResult(false, 400, "文件为空，请选择文件上传", null);
        }

        // 获取部署路径
        String realPath = request.getServletContext().getRealPath("/upload/");
        File uploadDir = new File(realPath);

        // 确保upload目录存在
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 获取原文件名
        String originalFilename = file.getOriginalFilename();

        // 处理没有扩展名的文件
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            int lastIndexOfDot = originalFilename.lastIndexOf('.');
            if (lastIndexOfDot != -1) {
                fileExtension = originalFilename.substring(lastIndexOfDot);
            }
        }

        // 生成新文件名
        String newFileName = System.currentTimeMillis() + fileExtension;

        // 文件上传路径
        File filePath = new File(realPath, newFileName);

        try {
            file.transferTo(filePath);
            
            // 返回给前端响应
            HashMap<String, String> map = new HashMap<>();
            map.put("fileName", newFileName);
            map.put("filePath", request.getContextPath() + "/upload/" + newFileName);
            return new ResponseResult(true, 200, "上传成功", map);
        } catch (IOException e) {
            return new ResponseResult(false, 500, "文件上传失败: " + e.getMessage(), null);
        } catch (Exception e) {
            return new ResponseResult(false, 500, "服务器内部错误: " + e.getMessage(), null);
        }
    }


    /**
     *
     * 新增课程信息和讲师信息
     */
    @RequestMapping("/saveOrUpdateCourse")
    public ResponseResult saveOrUpdateCourse (@RequestBody CourseVo courseVo) {
        if (courseVo.getId() == null){
            //如果传过来的id为空就执行新增
            try {
                //调用service
                courseService.saveCourseOrTeacher(courseVo);
                ResponseResult result = new ResponseResult(true, 200, "新增成功", null);
                return result;
            } catch (Exception e) {
                return new ResponseResult(false, 500, "新增失败: " + e.getMessage(), null);
            }
        }else {
            //如果传过来的id不为空就执行修改
            try {
                courseService.updateCourseOrTeacher(courseVo);
                ResponseResult result = new ResponseResult(true, 200, "修改成功", null);
                return result;
           }catch (Exception e) {
                return new ResponseResult(false, 500, "修改失败: " + e.getMessage(), null);
            }
        }

/*        try {
            //调用service
            courseService.saveCourseOrTeacher(courseVo);
            ResponseResult result = new ResponseResult(true, 200, "保存成功", null);
            return result;
        } catch (Exception e) {
            return new ResponseResult(false, 500, "保存失败: " + e.getMessage(), null);
        }*/
    }

    @RequestMapping("/findCourseById")
    public ResponseResult findCourseById(Integer id) {
        try {
            //调用service
            CourseVo courseVo = courseService.findCourseById(id);
            ResponseResult result = new ResponseResult(true, 200, "查询成功", courseVo);
            return result;
        } catch (Exception e) {
            return new ResponseResult(false, 500, "查询失败: " + e.getMessage(), null);
        }
    }

    @RequestMapping(path = "/updateCourseStatus", method = RequestMethod.GET)
    public ResponseResult updateCourseStatus(@RequestParam(value = "id", required = true) Integer id, 
                                             @RequestParam(value = "status", required = false) Integer status) {
        // 参数校验
        if (id == null) {
            return new ResponseResult(false, 500, "课程ID不能为空", null);
        }
        
        if (status == null) {
            return new ResponseResult(false, 500, "课程状态不能为空", null);
        }
        
        // 状态值有效性校验
        if (status != 0 && status != 1) {
            return new ResponseResult(false, 500, "课程状态只能为0（下架）或1（上架）", null);
        }

        try {
            //执行修改操作
            courseService.updateCourseStatus(id, status);
            // 查询更新后的课程信息，确保返回的是数据库中的实际值
            CourseVo courseVo = courseService.findCourseById(id);
            //保存修改后的状态,并返回
            Map<String,Object> map = new HashMap<>();
            map.put("status", courseVo.getStatus());
            ResponseResult result = new ResponseResult(true,200,"响应成功",map);
            return result;
        } catch (Exception e) {
            return new ResponseResult(false, 500, "更新失败: " + e.getMessage(), null);
        }
    }

}